package com.itqf.utils;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.*;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.avg.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.cardinality.ParsedCardinality;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import java.io.IOException;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/12/19
 * @Time: 下午5:45
 */
public class ESUtils {

    private  static final  String  index="shop";//数据库 database
    private  static final  String  type="book";//数据库  table

    public static RestHighLevelClient createClient() {
        HttpHost httpHost = new HttpHost("10.9.48.183", 9200);
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }


    public static boolean exists(String indexName) {
        try {
            //1,构建http请求对象
            GetIndexRequest request = new GetIndexRequest();
            request.indices(indexName);

            //2.索引是否存在
            boolean f = createClient().indices().exists(request, RequestOptions.DEFAULT);

            System.out.println(indexName + "存在与否" + f);

            return  f;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  false;

    }

    public  static boolean  deleteIndex(){
        try {
            //1.创建删除索引的请求对象
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest();
            deleteIndexRequest.indices(index);

            //2.通过客户端对象 删除索引
            AcknowledgedResponse response =  createClient().indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);

            //3.得到删除结果
            return response.isAcknowledged();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  false;


    }


    public static  boolean  createIndex(){
        try {
            //1.请求对象
            CreateIndexRequest createIndexRequest = new CreateIndexRequest();
            createIndexRequest.index(index);

            //2.设置索引的配置  分片  从
            //"settings": {
            //    "number_of_shards": 3,
            //    "number_of_replicas": 1
            //  }
            Settings.Builder settings = Settings.builder().put("number_of_shards",3)
                    .put("number_of_replicas",1);
            createIndexRequest.settings(settings);

            //3.设置索引的类型和映射信息（表和字段）
//        "properties":{
//            "id":{
//                   "type":"integer",
//                        "index":true,
//                        "store":true
//            },
            XContentBuilder mappings = JsonXContent.
                    contentBuilder()
                    .startObject() //{
                        .startObject("properties") // "properties":{
                            .startObject("id") //"id":{
                                   .field("type","integer").
                                    field("index",true)
                            .endObject()  //}
                            .startObject("title")
                                    .field("type","text")
                                    .field("analyzer","ik_smart")
                            .endObject()
                            .startObject("price")
                                    .field("type","float")
                            .endObject()
                            .startObject("author")
                                    .field("type","keyword")
                            .endObject()
                        .endObject()
                    .endObject();

            //文本类型：  text(分词，不支持聚合查询)|keyword（不分词，聚合查询）
            createIndexRequest.mapping(type,mappings);

            //4.创建索引
             AcknowledgedResponse response =  createClient().indices().create(createIndexRequest,RequestOptions.DEFAULT);

             return  response.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  false;
    }

    public  static  void  add(String json,String id){
        try {
            //1,创建请求对象
            IndexRequest indexRequest = new IndexRequest(index,type,id);
            indexRequest.source(json,XContentType.JSON);

            //2.新增数据
            IndexResponse response =  createClient().index(indexRequest,RequestOptions.DEFAULT);

            //3.得到结果
            System.out.println(response.status());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public  static  void  update(String json,String id){
        try {
            //1,创建请求对象
            UpdateRequest updateRequest = new UpdateRequest(index,type,id);
            updateRequest.doc(json,XContentType.JSON);

            //2.跟新数据
            UpdateResponse  response =  createClient().update(updateRequest,RequestOptions.DEFAULT);
            //3.得到结果
            System.out.println(response.status());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public  static  void  delete(String id){
        try {
            //1,创建请求对象
            DeleteRequest deleteRequest = new DeleteRequest(index,type,id);
            //deleteRequest.id(id);

            //2.跟新数据
            DeleteResponse response =  createClient().delete(deleteRequest,RequestOptions.DEFAULT);
            //3.得到结果
            System.out.println(response.status());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 精确查询
     */
    public static  void termQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型
            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.termQuery("author","小红"));
            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
/**
 *  "hits" : {
 *     "total" : 56,
 *     "max_score" : 1.0,
 *     "hits" : [
 *      {
 *         "_source" : {
 *           "id" : 79,
 *           "title" : "天龙八部",
 *           "author" : "金庸",
 *           "picpath" : null,
 *           "publishdate" : "2018-02-21T16:00:00.000+00:00"
 *         }
 */         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 精确查询
     * or
     */
    public static  void termsQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型
            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //author ='小红' or author ='小红1'  or author ='小红2'
             searchSourceBuilder.query(QueryBuilders.termsQuery("author","小红","小红1","小红2"));
            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
        /**
         *  "hits" : {
         *     "total" : 56,
         *     "max_score" : 1.0,
         *     "hits" : [
         *      {
         *         "_source" : {
         *           "id" : 79,
         *           "title" : "天龙八部",
         *           "author" : "金庸",
         *           "picpath" : null,
         *           "publishdate" : "2018-02-21T16:00:00.000+00:00"
         *         }
         */         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 全查查询
     *
     */
    public static  void matchAllQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //author ='小红' or author ='小红1'  or author ='小红2'
            //searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            searchSourceBuilder.query(new MatchAllQueryBuilder());
            searchSourceBuilder.size(100);//返回100条  默认是10条

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
/**
 *  "hits" : {
 *     "total" : 56,
 *     "max_score" : 1.0,
 *     "hits" : [
 *      {
 *         "_source" : {
 *           "id" : 79,
 *           "title" : "天龙八部",
 *           "author" : "金庸",
 *           "picpath" : null,
 *           "publishdate" : "2018-02-21T16:00:00.000+00:00"
 *         }
 */         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * 分词匹配查询
     *
     */
    public static  void matchQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.matchQuery("title","老王 小红").operator(Operator.OR));
            searchSourceBuilder.size(100);//返回100条  默认是10条

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
/**
 *  "hits" : {
 *     "total" : 56,
 *     "max_score" : 1.0,
 *     "hits" : [
 *      {
 *         "_source" : {
 *           "id" : 79,
 *           "title" : "天龙八部",
 *           "author" : "金庸",
 *           "picpath" : null,
 *           "publishdate" : "2018-02-21T16:00:00.000+00:00"
 *         }
 */         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * 分词匹配查询
     *
     */
    public static  void multiMatchQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //"author","title" 中只要有一个带有关键字就能查询出来
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery("小红","author","title"));
            searchSourceBuilder.size(100);//返回100条  默认是10条

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
/**
 *  "hits" : {
 *     "total" : 56,
 *     "max_score" : 1.0,
 *     "hits" : [
 *      {
 *         "_source" : {
 *           "id" : 79,
 *           "title" : "天龙八部",
 *           "author" : "金庸",
 *           "picpath" : null,
 *           "publishdate" : "2018-02-21T16:00:00.000+00:00"
 *         }
 */         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public   static  void  findById(String id){
        try {
            //1.请求对象
            GetRequest getRequest = new GetRequest(index,type,id);
            //2.查询
            GetResponse response =  createClient().get(getRequest,RequestOptions.DEFAULT);

            //3.结果
            System.out.println( response.getSourceAsMap());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 分词匹配查询
     *
     */
    public static  void findByIds(String[] ids){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //"author","title" 中只要有一个带有关键字就能查询出来

            searchSourceBuilder.query(QueryBuilders.idsQuery().addIds(ids));

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void prefixQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //"author","title" 中只要有一个带有关键字就能查询出来

            searchSourceBuilder.query(QueryBuilders.prefixQuery("title","小白"));

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void fuzzyQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

           //prefixLength(2)
            //大致类似 就能查询出结果
            searchSourceBuilder.query(QueryBuilders.fuzzyQuery("title","葵花宝宝").fuzziness(Fuzziness.AUTO));

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static  void regxepQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //prefixLength(2)
            //大致类似 就能查询出结果
            searchSourceBuilder.query(QueryBuilders.regexpQuery("author","小红[0-9]{1,}"));
            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void wildCardQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //prefixLength(2)
            //大致类似 就能查询出结果
            searchSourceBuilder.query(QueryBuilders.wildcardQuery("title","小白*"));

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void  pageQuery(int offset,int limit){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //prefixLength(2)
            //大致类似 就能查询出结果
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            //分页
            searchSourceBuilder.from(offset);
            searchSourceBuilder.size(limit);

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void  pageScrollQuery(int offset,int limit){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            searchRequest.scroll(TimeValue.timeValueMinutes(1l));

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //prefixLength(2)
            //大致类似 就能查询出结果
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            searchSourceBuilder.size(limit);

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            System.out.println("首页");
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }
             String scrollId =  searchResponse.getScrollId();
           // return scrollId;

            while(true){
                //scrollRequest
                SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);

                //设置scroll上下文有效时间
                scrollRequest.scroll(TimeValue.timeValueMinutes(1l));

                SearchResponse response =  createClient().scroll(scrollRequest,RequestOptions.DEFAULT);
                SearchHits searchHits1  = response.getHits();
                SearchHit hits[] =     searchHits1.getHits();
                if (hits!=null&&hits.length>0){
                    System.out.println("下一页");

                    for (SearchHit hit : hits) {

                        System.out.println(hit.getSourceAsMap());
                    }
                }else{
                    System.out.println("结束");
                    break;
                }



            }

            //最后 清空上下文
            ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
            clearScrollRequest.addScrollId(scrollId);


            ClearScrollResponse response =  createClient().clearScroll(clearScrollRequest,RequestOptions.DEFAULT);
            System.out.println(response.isSucceeded());

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public  static  void   deleteByQuery(){
        try {
            //1.构建请求对象
            DeleteByQueryRequest deleteByQueryRequest= new DeleteByQueryRequest(index);
            deleteByQueryRequest.types(type);
            //删除的条件
            //.gte("127"))  >=127
            //.lte("127")  <=127
            deleteByQueryRequest.setQuery(QueryBuilders.rangeQuery("id").gte("127"));
            //2.执行删除
            BulkByScrollResponse response = createClient().deleteByQuery(deleteByQueryRequest,RequestOptions.DEFAULT);
            System.out.println(response.getDeleted());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static  void  boolQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

            boolQueryBuilder.should(QueryBuilders.termQuery("title","红"));
            boolQueryBuilder.must(QueryBuilders.termQuery("author","小红1"));

            searchSourceBuilder.query(boolQueryBuilder);


            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void  boostingQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            /**
             * - positive：只有匹配上positive的查询的内容，才会被放到返回的结果集中。
             * - negative：如果匹配上和positive并且也匹配上了negative，就可以降低这样的文档score。
             * - negative_boost：指定系数，必须小于1.0
             */
            BoostingQueryBuilder boolQueryBuilder = new
                    BoostingQueryBuilder
                    (QueryBuilders.matchQuery("title","小红"),
                            QueryBuilders.prefixQuery("author","小红"))
                    .negativeBoost(0.9f);


            searchSourceBuilder.query(boolQueryBuilder);


            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);

            //
            SearchHits searchHits =  searchResponse.getHits();

            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println("score:"+hit.getScore());
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }



    public static  void filterQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            boolQueryBuilder.filter(QueryBuilders.termQuery("title","小红"));


            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.size(100);//返回100条  默认是10条

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
/**
 *  "hits" : {
 *     "total" : 56,
 *     "max_score" : 1.0,
 *     "hits" : [
 *      {
 *         "_source" : {
 *           "id" : 79,
 *           "title" : "天龙八部",
 *           "author" : "金庸",
 *           "picpath" : null,
 *           "publishdate" : "2018-02-21T16:00:00.000+00:00"
 *         }
 */         //
            SearchHits searchHits =  searchResponse.getHits();
            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static  void highLightQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//
            searchSourceBuilder.query(QueryBuilders.matchQuery("title","小红"));
            searchSourceBuilder.size(100);//返回100条  默认是10条

            //高亮部分
            HighlightBuilder highlightBuilder =new  HighlightBuilder();
            highlightBuilder.field("title");//关键字
            highlightBuilder.preTags("<font color=\"red\">");
            highlightBuilder.postTags("</font>");
            searchSourceBuilder.highlighter(highlightBuilder);

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
/**
 "hits" : {
 "total" : 41,
 "max_score" : 0.6254431,
 "hits" : [
 {
 "_index" : "shop",
 "_type" : "book",
 "_id" : "80",
 "_score" : 0.6254431,
 "_source" : {
 "id" : 80,
 "title" : "小红 小红 小红 小红 小红",
 "author" : "红",
 "picpath" : null,
 "publishdate" : null
 },
 "highlight" : {
 "title" : [
 "<font style='color:red'>小红</font> <font style='color:red'>小红</font> <font style='color:red'>小红</font> <font style='color:red'>小红</font> <font style='color:red'>小红</font>"
 ]
 }
 },
 */         //
            SearchHits searchHits =  searchResponse.getHits();

            SearchHit searchHit[] = searchHits.getHits();
            for (SearchHit hit : searchHit) {
                System.out.println(hit.getSourceAsMap());//非高亮
                System.out.println(hit.getHighlightFields());//高亮  //[隔壁老王和<font color="red">小红</font>不可说的往事8]]
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static  void aggrationQuery(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//

            searchSourceBuilder.aggregation(AggregationBuilders.cardinality("agg").field("author"));

            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
            // hits:{},
            //"aggregations" : {
            //    "agg" : {
            //      "value" : 55
            //    }
            ParsedCardinality map = searchResponse.getAggregations().get("agg");
            System.out.println("不重复的记录："+map+"----"+map.getValue());


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static  void aggrationQuery1(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//

            searchSourceBuilder.aggregation(AggregationBuilders.extendedStats("agg").field("price"));


            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
            // hits:{},
            //"aggregations" : {
            //    "agg" : {
            //      "value" : 55
            //    }
            ExtendedStats stats = searchResponse.getAggregations().get("agg");

            System.out.println("max:"+stats.getMax());
            System.out.println("min:"+stats.getMin());
            System.out.println("sum:"+stats.getSum());
            System.out.println("count:"+stats.getCount());

        } catch (IOException e) {
            e.printStackTrace();
        }


    }



    /**
     * 分组  聚合
     *select avg(price) from book  Group by  author;
     */

    public static  void aggrationQuery3(){
        try {
            //1.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            searchRequest.types(type);//指定类型

            //2.构建查询类型
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//

            //聚合查询
            /**
             *GET  /shop/book/_search
             * {
             *   "aggs": {
             *     "author_group": {// 自定义别名
             *       "terms": { //分组
             *         "field": "author",//分组的字段
             *       },
             *        "aggs": {//
             *          "avg_price": {//平均价格的别名
             *            "avg": {//分组后  求平均值
             *              "field": "price"
             *            }
             *          }
             *        }
             *     }
             *   }
             * }
             *
             */
            //按照作者分组
            AggregationBuilder aggregationBuilder =
                    AggregationBuilders.terms("author_group").field("author");
            //求每个作者出版的书籍的平均价格
            aggregationBuilder.subAggregation(AggregationBuilders.avg("avg_price").field("price"));
            //aggregationBuilder.subAggregation(AggregationBuilders.max("max_price").field("price"));


            searchSourceBuilder.aggregation(aggregationBuilder);//指定聚合查询
            searchRequest.source(searchSourceBuilder);//指定查询类型

            //3.执行请求
            SearchResponse searchResponse =   createClient().search(searchRequest,RequestOptions.DEFAULT);
            /**
             * "aggregations" : {
             *     "author_group" : {
             *       "doc_count_error_upper_bound" : 0,
             *       "sum_other_doc_count" : 32,
             *       "buckets" : [
             *         {
             *           "key" : "老王",
             *           "doc_count" : 5,
             *           "avg_price" : {
             *             "value" : 124.0
             *           }
             *         },
             */
           // System.out.println(searchResponse.getAggregations().get("author_group"));
            Aggregations aggregations = searchResponse.getAggregations();
            ParsedStringTerms terms = aggregations.get("author_group");
            List<? extends Terms.Bucket> list =  terms.getBuckets();
            for (Terms.Bucket bucket : list) {
                System.out.println("author:"+bucket.getKey()+"出版的书的平均价格：");
                ParsedAvg avg =  bucket.getAggregations().get("avg_price");
                System.out.println(avg.getValue());
            }

            // 每个类型下的商品平均价格?

        } catch (IOException e) {
            e.printStackTrace();
        }


    }






}